package com.tebiecloud.order.server.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beust.jcommander.internal.Maps;
import com.tebiecloud.act.client.model.entity.Act;
import com.tebiecloud.act.client.model.entity.ActGiftPack;
import com.tebiecloud.act.client.model.entity.ActGoodsRef;
import com.tebiecloud.base.client.constants.BaseConstants;
import com.tebiecloud.base.client.model.entity.BaseUser;
import com.tebiecloud.common.constants.OrderListConstants;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.constants.UserConstants;
import com.tebiecloud.common.model.PageParams;
import com.tebiecloud.common.mybatis.query.CriteriaQuery;
import com.tebiecloud.common.security.SecurityHelper;
import com.tebiecloud.common.security.SecurityUserDetails;
import com.tebiecloud.common.utils.*;
import com.tebiecloud.goods.client.model.entity.Goods;
import com.tebiecloud.goods.client.model.entity.GoodsSpecification;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinUser;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinUserExpand;
import com.tebiecloud.mpweixin.client.model.mpweixin.ActionInfo;
import com.tebiecloud.mpweixin.client.model.mpweixin.QrcodeParam;
import com.tebiecloud.mpweixin.client.model.mpweixin.QrcodeTicket;
import com.tebiecloud.mpweixin.client.model.mpweixin.Scene;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinUserWallet;
import com.tebiecloud.mpweixin.client.model.vo.DeductUserAmount;
import com.tebiecloud.order.client.constatns.OrderConstants;
import com.tebiecloud.order.client.model.entity.*;
import com.tebiecloud.order.client.model.vo.*;
import com.tebiecloud.order.server.service.*;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.order.server.service.feign.*;
import com.tebiecloud.retail.client.constants.RetailConstants;
import com.tebiecloud.retail.client.model.entity.RetailOrder;
import com.tebiecloud.store.client.model.entity.Store;
import com.tebiecloud.store.client.model.entity.StoreStaff;
import com.tebiecloud.yunst.client.constants.YunstConstants;
import com.tebiecloud.yunst.client.model.vo.PayInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.util.*;

/**
 * 订单 前端控制器
 *
 * @author tebie
 * @date 2019-09-15
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderrController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private OrderrService orderService;

    @Autowired
    private OrderGoodsService orderGoodsService;

    @Autowired
    private OrderStats2Service orderStats2Service;

    @Autowired
    private OrderRefundService orderRefundService;

    @Autowired
    private OrderContactLogService orderContactLogService;

    @Autowired
    private OrderWriteOffLogService orderWriteOffLogService;

    @Autowired
    private ActServiceClient actServiceClient;

    @Autowired
    private StoreStaffWalletServiceClient storeStaffWalletServiceClient;

    @Autowired
    private StoreFlowServiceClient storeFlowServiceClient;

    @Autowired
    private StoreStaffServiceClient storeStaffServiceClient;

    @Autowired
    private GoodsServiceClient goodsServiceClient;

    @Autowired
    private GoodsSpecificationServiceClient goodsSpecificationServiceClient;

    @Autowired
    private ActGoodsRefServiceClient actGoodsRefServiceClient;

    @Autowired
    private YunStPaymentServiceClient yunStPaymentServiceClient;

    @Autowired
    private RetailOrderServiceClient retailOrderServiceClient;

    @Autowired
    private MpweixinServiceClient mpweixinServiceClient;

    @Autowired
    private StoreServiceClient storeServiceClient;

    @Autowired
    private MpweixinApiServiceClient mpweixinApiServiceClient;

    @Autowired
    OrderStats1Service orderStats1Service;

    @Autowired
    BaseUserServiceClient baseUserServiceClient;

    @Autowired
    ReserveService reserveService;

    @Autowired
    ReserveGoodsService reserveGoodsService;

    @Autowired
    ReserveOrderService reserveOrderService;

    @Autowired
    private OrderEvaluateService orderEvaluateService;

    /**
     * 获取订单确认信息
     *
     * @param actId       //活动id
     * @param trolleyList //购物车列表
     * @param extraCost   //额外消费金额
     * @return
     */
    @PostMapping("createpre")
    public ResultBody createpre(
            @RequestParam(value = "actId", required = false) Long actId,
            @RequestParam(value = "trolleyList", required = false) String trolleyList,
            @RequestParam(value = "extraCost", required = false, defaultValue = "0") Integer extraCost
    ) {
        //校验活动
        if(actId != null && actId != 0){
            ResultBody resultBody = valiAct(actId);
            if(resultBody.getCode() != ResultEnum.OK.getCode()) return resultBody;
        }
        //校验参数
        if(StringUtils.isEmpty(trolleyList) && extraCost==0){
            return ResultBodyUtils.failedMsg("没有选择规格");
        }
        OrderConfirm orderConfirm = new OrderConfirm();
        //获取购物车列表
        List<GoodsSpecList> goodsSpecListList = getGoodsSpecList(actId, trolleyList);
        if(goodsSpecListList==null){
            return ResultBodyUtils.failedMsg("获取规格列表不存在");
        }
        int price = 0;//总价格
        //计算总价
        for (GoodsSpecList goodsSpecList : goodsSpecListList) {
            price = price + goodsSpecList.getAmount() * goodsSpecList.getPrice();
        }
        orderConfirm.setGoodsSpecList(goodsSpecListList);
        //加上其他服务价格
        orderConfirm.setPrice(price + extraCost);
        orderConfirm.setActId(actId);
        orderConfirm.setExtraCost(extraCost);
        // 获取当前用户信息
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        long userId = securityUserDetails.getUserId().longValue();
        // 获取用户历史最近一条订单信息
        Orderr order = orderService.getLastOne(userId);
        log.info(">>minjie 获取userId:{}最近一次订单:{}",userId,order);
        if (order != null) {
            orderConfirm.setReceiver(order.getReceiver());
            orderConfirm.setPhone(order.getPhone());
        }else{
            orderConfirm.setReceiver(securityUserDetails.getNickName());
        }
        // 获取用户钱包信息
        ResultBody<MpweixinUserWallet> mpweixinUserWalletResultBody = mpweixinServiceClient.selectUserWallet(userId);
        if (mpweixinUserWalletResultBody !=null && mpweixinUserWalletResultBody.getCode() == ResultEnum.OK.getCode()) {
            MpweixinUserWallet mpweixinUserWallet = mpweixinUserWalletResultBody.getData();
            if(mpweixinUserWallet!=null){
                //给最大余额
                orderConfirm.setBalance(mpweixinUserWallet.getBalance()==null?0:mpweixinUserWallet.getBalance());
            }
        }
        // 支付金额
        int payPrice = orderConfirm.getPrice() - orderConfirm.getBalance();
        orderConfirm.setPayPrice(payPrice<=0?0:payPrice);
        //查询前面还有多少预约
        Map<String,Integer> resultMap = getRemain(goodsSpecListList.get(0).getStoreId());
        orderConfirm.setServiceWaitNumber(resultMap.get("serviceWaitNumber"));
        orderConfirm.setServiceWaitTime(resultMap.get("serviceWaitTime"));
        //获取门店信息
        ResultBody<Store> storeResultBody = storeServiceClient.getStore(goodsSpecListList.get(0).getStoreId());
        if(storeResultBody!=null && storeResultBody.getCode() == ResultEnum.OK.getCode()){
            Store store = storeResultBody.getData();
            if(store!=null){
                orderConfirm.setStoreName(store.getName());
            }
        }
        return ResultBodyUtils.ok(orderConfirm);
    }

    /**
     * 查询还需等待多少
     * @return
     */
    private Map<String,Integer> getRemain(long storeId){
        Map<String,Integer> reultMap = com.google.common.collect.Maps.newHashMap();
        List<Long> statusList = Lists.newArrayList();
        statusList.add(1L);
        statusList.add(2L);
        statusList.add(3L);
        statusList.add(4L);
        QueryWrapper<Reserve> reserveQueryWrapper = new QueryWrapper<>();
        reserveQueryWrapper.eq("store_id",storeId);
        reserveQueryWrapper.lt("ct",new Date());
        reserveQueryWrapper.in("status",statusList);
        List<Reserve> reserveList = reserveService.list(reserveQueryWrapper);
        int serviceWaitNumber = 0;//服务人数
        int serviceWaitTime = 0;//服务时长：单位：分钟
        if(reserveList!=null && reserveList.size()>0){
            serviceWaitNumber = reserveList.size();
            for(Reserve reserve1:reserveList){
                List<ReserveGoods> reserveGoodsList = getReserveGoodsList(reserve1);
                if(reserveGoodsList!=null && reserveGoodsList.size()>0){
                    for(ReserveGoods reserveGoods:reserveGoodsList){
                        long currentTime = System.currentTimeMillis();//当前时间
                        Long remainTime = 0L;//剩余时间(分钟)
                        if(reserve1.getStatus()==3 || reserve1.getStatus()==4){
                            //计算可能剩余多少分钟
                            if(reserve1.getStartTime()!=null){
                                long differentTime = currentTime-reserve1.getStartTime().getTime();
                                log.info(">>minjie 服务id：{},已经开始服务多少时间：{}毫秒",reserve1.getReserveId(),differentTime);
                                if(reserveGoods.getServiceTime()!=null){
                                    if(reserveGoods.getServiceTime()*60*1000-differentTime>0){
                                        remainTime = (reserveGoods.getServiceTime()*60*1000-differentTime)/(1000*60);
                                    }
                                }
                                log.info(">>minjie 服务id：{},剩余多少时间：{}分钟",reserve1.getReserveId(),remainTime);
                            }
                            serviceWaitTime = serviceWaitTime+remainTime.intValue();
                        }else{
                            serviceWaitTime = serviceWaitTime+reserveGoods.getServiceTime();
                        }
                    }
                }
            }
            //如果服务中小于坑数
            if(serviceWaitNumber<OrderConstants.RESERVE_NUM){
                serviceWaitTime = 0;
            }
        }
        reultMap.put("serviceWaitNumber",serviceWaitNumber);
        reultMap.put("serviceWaitTime",serviceWaitTime);
        return reultMap;
    }

    /**
     * 获取预约服务信息
     * @param reserve
     * @return
     */
    private List<ReserveGoods> getReserveGoodsList(Reserve reserve){
        QueryWrapper<ReserveGoods> reserveGoodsQueryWrapper = new QueryWrapper<>();
        reserveGoodsQueryWrapper.eq("reserve_id",reserve.getReserveId());
        List<ReserveGoods> reserveGoodsList = reserveGoodsService.list(reserveGoodsQueryWrapper);
        return reserveGoodsList;
    }

    /**
     * 获取预约订单确认信息
     * @param reserveId 预约id
     * @return
     */
    @PostMapping("createbyreservepre")
    public ResultBody createbyreservepre(
            @RequestParam(value = "reserveId") long reserveId
    ) {
        // 用户信息
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();

        // 获取预约信息
        QueryWrapper<Reserve> reserveQueryWrapper = new QueryWrapper<>();
        reserveQueryWrapper.eq("reserve_id",reserveId);
        Reserve reserve = reserveService.getOne(reserveQueryWrapper, false);
        if(reserve == null || securityUserDetails.getUserId().longValue() != reserve.getUserId().longValue()) {
            log.info("xiaoc>> 预约信息不存在, userId: {}, reserve: {}", securityUserDetails.getUserId(), JsonUtils.Obj2Str(reserve));
            return ResultBodyUtils.failed("预约信息不存在");
        }

        // 是否已创建订单
        QueryWrapper<ReserveOrder> queryWrapperReserveOrder = new QueryWrapper<>();
        queryWrapperReserveOrder.eq("reserve_id", reserveId);
        queryWrapperReserveOrder.orderByDesc("ct");
        ReserveOrder reserveOrder = reserveOrderService.getOne(queryWrapperReserveOrder, false);
        if(reserveOrder != null && reserveOrder.getOrderId() != null && reserveOrder.getOrderId() > 0) {
            Orderr orderr = orderService.getById(reserveOrder.getOrderId());
            if(orderr != null && orderr.getStatus() != null && orderr.getStatus() >= 2) {
                Map<String, Object> respData = Maps.newHashMap();
                respData.put("orderId", orderr.getOrderId());
                return ResultBodyUtils.ok(respData);
            }
        }

        // 基础信息
        OrderConfirm orderConfirm = new OrderConfirm();
        orderConfirm.setReserveId(reserveId);
        orderConfirm.setReceiver(reserve.getReceiver());
        orderConfirm.setPhone(reserve.getPhone());

        // 预约商品信息
        QueryWrapper<ReserveGoods> queryWrapperReserveGoods = new QueryWrapper();
        queryWrapperReserveGoods.eq("reserve_id", reserveId);
        ReserveGoods reserveGoods = reserveGoodsService.getOne(queryWrapperReserveGoods, false);
        if(reserveGoods != null) {
            // 价格信息
            orderConfirm.setPrice(reserveGoods.getTotalPrice());
            // 获取用户钱包信息
            ResultBody<MpweixinUserWallet> mpweixinUserWalletResultBody = mpweixinServiceClient.selectUserWallet(reserve.getUserId());
            if (mpweixinUserWalletResultBody != null && mpweixinUserWalletResultBody.getCode() == ResultEnum.OK.getCode()) {
                MpweixinUserWallet mpweixinUserWallet = mpweixinUserWalletResultBody.getData();
                if(mpweixinUserWallet != null && mpweixinUserWallet.getBalance() != null) {
                    //给最大余额
                    orderConfirm.setBalance(Math.min(mpweixinUserWallet.getBalance(), orderConfirm.getPrice()));
                }
            }
            // 支付金额
            orderConfirm.setPayPrice(orderConfirm.getPrice() - orderConfirm.getBalance());

            //获取门店信息
            ResultBody<Store> storeResultBody = storeServiceClient.getStore(reserveGoods.getStoreId());
            if(storeResultBody != null && storeResultBody.getCode() == ResultEnum.OK.getCode()) {
                Store store = storeResultBody.getData();
                if(store != null){
                    orderConfirm.setStoreName(store.getName());
                }
            }

            // 商品信息
            GoodsSpecList goodsSpecList = new GoodsSpecList();
            goodsSpecList.setGoodsId(reserveGoods.getGoodsId());
            goodsSpecList.setGoodsPic(reserveGoods.getGoodsPic());
            goodsSpecList.setGoodsName(reserveGoods.getGoodsName());
            goodsSpecList.setSpecId(reserveGoods.getGoodsSpecificationId());
            goodsSpecList.setSpecName(reserveGoods.getSpecificationName());
            goodsSpecList.setPrice(reserveGoods.getTotalPrice());
            goodsSpecList.setAmount(reserveGoods.getAmount());
            List<GoodsSpecList> goodsSpecListList = Lists.newArrayList();
            goodsSpecListList.add(goodsSpecList);
            orderConfirm.setGoodsSpecList(goodsSpecListList);
        }

        return ResultBodyUtils.ok(orderConfirm);
    }

    /**
     * 校验活动
     * @param actId
     * @return
     */
    private ResultBody valiAct(long actId){
        long timestamp = System.currentTimeMillis();
        //查询活动信息
        ResultBody<Act> actResultBody = actServiceClient.selectActByActId(actId);
        if(actResultBody!=null && actResultBody.getCode() == ResultEnum.OK.getCode()){
            Act act = actResultBody.getData();
            if(act==null){
                //活动不存在
                return ResultBodyUtils.build(com.tebiecloud.act.client.constants.ResultEnum.ACT_NOT_EXIT.getCode(),
                        com.tebiecloud.act.client.constants.ResultEnum.ACT_NOT_EXIT.getMessage());
            }
            if(act.getStatus().equals(0)){
                //活动已禁用
                return ResultBodyUtils.build(com.tebiecloud.act.client.constants.ResultEnum.ACT_STATUS_ERROR.getCode(),
                        com.tebiecloud.act.client.constants.ResultEnum.ACT_STATUS_ERROR.getMessage());
            }
            if(act.getEndTime().getTime()<timestamp){
                //活动已过期
                return ResultBodyUtils.build(com.tebiecloud.act.client.constants.ResultEnum.ACT_TIMEOUT.getCode(),
                        com.tebiecloud.act.client.constants.ResultEnum.ACT_TIMEOUT.getMessage());
            }
        }
        return ResultBodyUtils.ok();
    }

    /**
     * 获取购物车列表
     *
     * @param actId
     * @param trolleyList [{"goodsSpecificationId":16151,"amount":1},{"goodsSpecificationId":16111,"amount":2}]
     * @return
     */
    private List<GoodsSpecList> getGoodsSpecList(Long actId, String trolleyList) {
        if(StringUtils.isEmpty(trolleyList))return null;
        //字符串转对象列表
        JSONArray jsonArray = JSONArray.parseArray(trolleyList);
        List<TrolleyList> trolleyLists = jsonArray.toJavaList(TrolleyList.class);
        // 获取活动信息
        List<GoodsSpecList> goodsSpecListList = new ArrayList<>();
        if (actId == null || actId == 0) {
            //普通商品
            for (TrolleyList trolleyList1 : trolleyLists) {
                ResultBody<GoodsSpecification> goodsSpecificationResultBody = goodsSpecificationServiceClient.infoGoodsSpecification(trolleyList1.getGoodsSpecificationId());
                if (goodsSpecificationResultBody != null && goodsSpecificationResultBody.getCode() == ResultEnum.OK.getCode()) {
                    GoodsSpecification goodsSpecification = goodsSpecificationResultBody.getData();
                    GoodsSpecList goodsSpecList = new GoodsSpecList();
                    goodsSpecList.setGoodsId(goodsSpecification.getGoodsId());
                    goodsSpecList.setAmount(trolleyList1.getAmount());
                    goodsSpecList.setPrice(goodsSpecification.getPrice());
                    goodsSpecList.setSpecId(goodsSpecification.getSpecId());
                    goodsSpecList.setSpecName(goodsSpecification.getName());
                    //计算获利=销售价*佣金比例*数量
                    Double profit = goodsSpecification.getPrice()*(Double.valueOf(goodsSpecification.getCommissionRate())/100)*trolleyList1.getAmount();
                    goodsSpecList.setProfit(profit.intValue());
                    goodsSpecList.setCoin(goodsSpecification.getCoin()*trolleyList1.getAmount());
                    //查询商品信息
                    ResultBody<List<Goods>> goodsResult = goodsServiceClient.selectByGoodsIds(goodsSpecification.getGoodsId().toString());
                    if (goodsResult != null && goodsResult.getCode() == ResultEnum.OK.getCode()) {
                        List<Goods> goodsList = goodsResult.getData();
                        if (goodsList.size() > 0) {
                            goodsSpecList.setStoreId(goodsList.get(0).getStoreId());
                            goodsSpecList.setGoodsName(goodsList.get(0).getName());
                            goodsSpecList.setGoodsPic(goodsList.get(0).getSharePic());//使用正方形的图
                            goodsSpecList.setDesc(goodsList.get(0).getDes());//设置使用规格
                        }
                    }
                    goodsSpecListList.add(goodsSpecList);
                }
            }
        } else {
            Act act = null;
            //查询活动信息
            ResultBody<Act> actResultBody = actServiceClient.selectActByActId(actId);
            if(actResultBody != null && actResultBody.getCode() == ResultEnum.OK.getCode()){
                act = actResultBody.getData();
                if(act==null)return null;
            }else{
                return null;
            }
            ActGiftPack actGiftPack = null;
            if(act.getActType() == 2){//如果是体验活动
                ResultBody<ActGiftPack>  actGiftPackResultBody = actServiceClient.selectActGift(actId);
                if(actGiftPackResultBody!=null && actGiftPackResultBody.getCode() == ResultEnum.OK.getCode()){
                    actGiftPack = actGiftPackResultBody.getData();
                    if(actGiftPack == null)return null;
                }else{
                    return null;
                }
            }
            //活动商品
            for (TrolleyList trolleyList1 : trolleyLists) {
                //查询活动规格信息
                ResultBody<List<ActGoodsRef>> actGoodsRefResultBody = actGoodsRefServiceClient.listActGoodsRef(actId, trolleyList1.getGoodsSpecificationId());
                if (actGoodsRefResultBody != null && actGoodsRefResultBody.getCode() == ResultEnum.OK.getCode()) {
                    List<ActGoodsRef> actGoodsRefList = actGoodsRefResultBody.getData();
                    GoodsSpecList goodsSpecList = new GoodsSpecList();
                    if (actGoodsRefList.size() > 0) {
                        goodsSpecList.setGoodsId(actGoodsRefList.get(0).getGoodsId());
                        goodsSpecList.setAmount(trolleyList1.getAmount());
                        goodsSpecList.setSpecId(actGoodsRefList.get(0).getSpecId());
                        if(actGiftPack == null){//限时促销活动计算
                            //计算获利=销售价*佣金比例*数量
                            Double profit = actGoodsRefList.get(0).getPrice()*(Double.valueOf(actGoodsRefList.get(0).getCommissionRate())/100)*trolleyList1.getAmount();
                            goodsSpecList.setProfit(profit.intValue());
                            goodsSpecList.setPrice(actGoodsRefList.get(0).getPrice());
                        }else if(actGiftPack != null){//体验活动
                            //计算获利=销售价*佣金比例*数量
                            Double profit = actGiftPack.getPrice()*(Double.valueOf(actGiftPack.getCommissionRate())/100)*trolleyList1.getAmount();
                            goodsSpecList.setProfit(profit.intValue());
                            goodsSpecList.setPrice(actGiftPack.getPrice());
                        }
                        //查询商品信息
                        ResultBody<List<Goods>> goodsResult = goodsServiceClient.selectByGoodsIds(actGoodsRefList.get(0).getGoodsId().toString());
                        if (goodsResult != null && goodsResult.getCode() == ResultEnum.OK.getCode()) {
                            List<Goods> goodsList = goodsResult.getData();
                            if (goodsList.size() > 0) {
                                goodsSpecList.setStoreId(goodsList.get(0).getStoreId());
                                goodsSpecList.setGoodsName(goodsList.get(0).getName());
                                goodsSpecList.setGoodsPic(goodsList.get(0).getSharePic());//使用正方形的图
                            }
                        }
                        //查询规格信息
                        ResultBody<GoodsSpecification> goodsSpecificationResultBody = goodsSpecificationServiceClient.infoGoodsSpecification(trolleyList1.getGoodsSpecificationId());
                        if (goodsSpecificationResultBody != null && goodsSpecificationResultBody.getCode() == ResultEnum.OK.getCode()) {
                            GoodsSpecification goodsSpecification = goodsSpecificationResultBody.getData();
                            goodsSpecList.setSpecName(goodsSpecification.getName());
                            //设置乖乖币
                            goodsSpecList.setCoin(goodsSpecification.getCoin()*trolleyList1.getAmount());
                        }
                    }
                    goodsSpecListList.add(goodsSpecList);
                }
            }
        }
        return goodsSpecListList;
    }

    /**
     * 提交订单
     *
     * @param actId     活动id,
     * @param receiver  收货人,
     * @param phone     手机号码,
     * @param extraCost //额外消费项目
     * @param payType   //支付方式：1微信，2现金，3刷卡
     * @return
     */
    @PostMapping("create")
    public ResultBody create(
            @RequestParam(value = "sourceUserId", required = false) Long sourceUserId,
            @RequestParam(value = "actId", required = false) Long actId,
            @RequestParam(value = "trolleyList", required = false) String trolleyList,
            @RequestParam(value = "receiver", required = false) String receiver,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "extraCost", required = false, defaultValue = "0") int extraCost,
            @RequestParam(value = "payType", required = false, defaultValue = "1") int payType,
            @RequestParam(value = "remark", required = false) String remark) {
        //校验活动
        if(actId != null && actId != 0){
            ResultBody resultBody = valiAct(actId);
            if(resultBody.getCode() != ResultEnum.OK.getCode()) return resultBody;
        }
        //校验参数
        if(StringUtils.isEmpty(trolleyList) && extraCost==0){
            return ResultBodyUtils.failedMsg("没有选择规格");
        }
        // 获取当前用户信息
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        long userId = securityUserDetails.getUserId();
        //获取openid
        MpweixinUserExpand mpweixinUserExpand = null;
        if(BaseConstants.ACCOUNT_DOMAIN_MP.equals(securityUserDetails.getDomain())){
            String[] username = securityUserDetails.getUsername().split(":");
            if(username.length>=2){
                //获取用户信息
                ResultBody<MpweixinUserExpand> mpweixinUserExpandResultBody = mpweixinServiceClient.selectUserInfo(userId,username[1]);
                if(mpweixinUserExpandResultBody!=null && mpweixinUserExpandResultBody.getCode() == ResultEnum.OK.getCode()){
                    mpweixinUserExpand = mpweixinUserExpandResultBody.getData();
                }
            }
        }
        //获取购物车列表
        List<GoodsSpecList> goodsSpecListList = getGoodsSpecList(actId, trolleyList);
        Orderr order = new Orderr();//订单信息
        Act act = null;//活动信息
        int profit = 0;//订单获利
        int price = 0;//订单金额
        int sold = 0;//没有销售状态
        int status = OrderConstants.ORDER_STATUS_PREPAY;//订单初始状态--待支付
        long storeId = 0; // 门店id
        int qty = 0;//计算购买数量
        if(goodsSpecListList!=null && goodsSpecListList.size()>0){
            for (GoodsSpecList goodsSpecList : goodsSpecListList) {
                price = price + goodsSpecList.getPrice() * goodsSpecList.getAmount();
                profit = profit + goodsSpecList.getProfit();
                qty = qty + goodsSpecList.getAmount();//计算购买数量
                if(storeId <= 0) {
                    storeId = goodsSpecList.getStoreId();
                }
            }
        }
        //加上额外消费
        price = price + extraCost;
        if (payType != 1) {//如果支付类型不是微信
            sold = 1;//则默认是已支付
            status = OrderConstants.ORDER_STATUS_COMPLETED;//则默认是已完成订单
        }
        if (actId == null || actId == 0) {
            //扣减普通商品库存
            if(goodsSpecListList!=null && goodsSpecListList.size()>0) {
                for (GoodsSpecList goodsSpecList : goodsSpecListList) {
                    ResultBody retUpdateStockQty = goodsSpecificationServiceClient.updateStockQty(goodsSpecList.getSpecId(), -goodsSpecList.getAmount());
                    if (retUpdateStockQty.getCode() != ResultEnum.OK.getCode()) {
                        return retUpdateStockQty;
                    }
                }
            }
        } else {
            //查询活动信息
            ResultBody<Act> actResultBody = actServiceClient.selectActByActId(actId);
            if (actResultBody != null && actResultBody.getCode() == ResultEnum.OK.getCode()) {
                act = actResultBody.getData();
                if(act!=null){
                    if(act.getPurchaseQty()!=-1){//-1表示可以多次购买
                        //查询之前购买的订单
                        QueryWrapper<Orderr> orderrQueryWrapper = new QueryWrapper<>();
                        orderrQueryWrapper.eq("user_id",userId);
                        orderrQueryWrapper.eq("act_id",act.getActId());
                        orderrQueryWrapper.gt("status",0);
                        int orderCount = orderService.count(orderrQueryWrapper);
                        if(orderCount>=1){
                            return ResultBodyUtils.failedMsg("已达到购买次数，不能再购买");
                        }
                        if(qty>act.getPurchaseQty()){
                            return ResultBodyUtils.failedMsg("此活动每人限购"+act.getPurchaseQty());
                        }
                    }
                    order.setActId(actId);
                    order.setActName(act.getName());
                    order.setActPic(act.getMainPic());
                    order.setActType(act.getActType());
                }
            }
            //扣减活动商品库存
            if(goodsSpecListList!=null && goodsSpecListList.size()>0) {
                for (GoodsSpecList goodsSpecList : goodsSpecListList) {
                    ResultBody retUpdateStockQty = actServiceClient.updateStockQty(actId, goodsSpecList.getSpecId(), -goodsSpecList.getAmount());
                    if (retUpdateStockQty.getCode() != ResultEnum.OK.getCode()) {
                        return retUpdateStockQty;
                    }
                }
            }
        }

        // 扣减用户钱包
        int deductBalance = 0; // 余额扣费额度
        int deductCoin = 0; // 乖乖币扣费额度
        ResultBody<DeductUserAmount> deductUserAmountResultBody = mpweixinServiceClient.updateDeductAmount(securityUserDetails.getUserId(), price, 0);
        if (deductUserAmountResultBody.getCode() == ResultEnum.OK.getCode() && deductUserAmountResultBody.getData() != null) {
            DeductUserAmount deductUserAmount = deductUserAmountResultBody.getData();
            if(deductUserAmount!=null){
                deductBalance = deductUserAmount.getDeductBalance();
                deductCoin = deductUserAmount.getDeductCoin();
            }
        }
        // 创建订单
        order.setStoreId(storeId);
        order.setNumber(UUID.randomUUID().toString().replaceAll("-", ""));
        order.setUserId(securityUserDetails.getUserId());
        order.setPhone(phone);
        order.setReceiver(receiver==null?UserConstants.nickName:receiver);
        if(mpweixinUserExpand!=null){
            order.setReceiverHeadimgurl(mpweixinUserExpand.getHeadimgurl()==null?UserConstants.headImageUrl:mpweixinUserExpand.getHeadimgurl());
        }
        order.setPayType(payType);
        order.setStatus(status);
        order.setPrice(price);
        order.setPayBalances(deductBalance);
        order.setPayMgg(deductCoin);
        order.setExtraCost(extraCost);
        order.setPayReady(order.getPrice() - order.getPayBalances());
        order.setRemark(remark);
        orderService.save(order);
        List<OrderGoods> orderGoodsList = saveBatchOrderGoods(order.getOrderId(),userId, goodsSpecListList, sold, act);

        //分享记录
        if(sourceUserId!=null){
            retailOrderServiceClient.saveRetailOrder(sourceUserId,order.getOrderId(),profit,securityUserDetails.getUserId(),status);
        }
        // 创建支付信息
        if (order.getPayReady() > 0 && payType == 1) {
            String[] arrUsername = securityUserDetails.getUsername().split(":"); // username格式为：公众号appid:openid
            if (arrUsername.length >= 2) {
                ResultBody<PayInfoVO> retPayInfoVO = yunStPaymentServiceClient.consumeApply(securityUserDetails.getUserId(),
                        order.getOrderId(), order.getPayReady(), YunstConstants.PAY_METHOD_WEIXIN, arrUsername[1], OrderConstants.PAY_OUTTIME);
                PayInfoVO payInfoVO = retPayInfoVO.getData();
                if(payInfoVO!=null) {//返回支付单号和实际支付金额
                    payInfoVO.setOrderId(order.getOrderId());
                    payInfoVO.setPayReady(order.getPayReady());
                }
                return retPayInfoVO;
            } else {
                log.error("xiaoc>> 从缓存中获取微信用户openid失败，username: {}", securityUserDetails.getUsername());
            }
        } else if(order.getPayReady()==0 ){
            // 处理订单全余额购买
            orderPaySuccess(order,orderGoodsList,securityUserDetails);

        }
        //返回支付单号和实际支付金额
        PayInfoVO payInfoVO = new PayInfoVO();
        payInfoVO.setOrderId(order.getOrderId());
        payInfoVO.setPayReady(order.getPayReady());
        return ResultBodyUtils.ok(payInfoVO);
    }

    /**
     * 通过排队单号创建订单
     * @param reserveId
     * @return
     */
    @PostMapping("createbyreserve")
    public ResultBody createByReserve(@RequestParam(value = "reserveId") long reserveId) {
        // 获取当前用户信息
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();

        // 是否已创建订单
        QueryWrapper<ReserveOrder> queryWrapperReserveOrder = new QueryWrapper<>();
        queryWrapperReserveOrder.eq("reserve_id", reserveId);
        queryWrapperReserveOrder.orderByDesc("ct");
        ReserveOrder reserveOrder = reserveOrderService.getOne(queryWrapperReserveOrder, false);

        Orderr order = null;
        OrderGoods orderGoods = null;
        if(reserveOrder == null) {
            Reserve reserve = reserveService.getById(reserveId);
            if(reserve == null || reserve.getUserId().longValue() != securityUserDetails.getUserId()) {
                log.info("xiaoc>> 排队取号信息不存在，reserveId: {}", reserveId);
                return ResultBodyUtils.failedMsg("信息不存在");
            }
            QueryWrapper<ReserveGoods> queryWrapperReserveGoods = new QueryWrapper<>();
            queryWrapperReserveGoods.eq("reserve_id", reserveId);
            queryWrapperReserveGoods.orderByDesc("ct");
            ReserveGoods reserveGoods = reserveGoodsService.getOne(queryWrapperReserveGoods, false);
            if (reserveGoods == null) {
                log.info("xiaoc>> 排队取号服务信息不存在，reserveId: {}", reserveId);
                return ResultBodyUtils.failedMsg("服务不存在");
            }

            // 扣减用户钱包
            int deductBalance = 0; // 余额扣费额度
            int deductCoin = 0; // 乖乖币扣费额度
            ResultBody<DeductUserAmount> deductUserAmountResultBody = mpweixinServiceClient.updateDeductAmount(reserve.getUserId(), reserveGoods.getTotalPrice(), 0);
            if (deductUserAmountResultBody.getCode() == ResultEnum.OK.getCode() && deductUserAmountResultBody.getData() != null) {
                DeductUserAmount deductUserAmount = deductUserAmountResultBody.getData();
                if(deductUserAmount != null){
                    deductBalance = deductUserAmount.getDeductBalance();
                    deductCoin = deductUserAmount.getDeductCoin();
                }
            }
            // 创建订单
            Act act = null;
            order = new Orderr();
            if(reserve.getActId() != null && reserve.getActId() > 0) {
                // 获取活动信息
                order.setActId(reserve.getActId());
                ResultBody<Act> actResultBody = actServiceClient.selectActByActId(reserve.getActId());
                if (actResultBody != null && actResultBody.getCode() == ResultEnum.OK.getCode()) {
                    act = actResultBody.getData();
                    if (act != null) {
                        order.setActName(act.getName());
                        order.setActPic(act.getMainPic());
                        order.setActType(act.getActType());
                    }
                }
            }
            order.setStoreId(reserve.getStoreId());
            order.setNumber(UUID.randomUUID().toString().replaceAll("-", ""));
            order.setUserId(reserve.getUserId());
            order.setPhone(reserve.getPhone());
            order.setReceiver(reserve.getReceiver());
            order.setReceiverHeadimgurl(reserve.getReceiverHeadimgurl());
            order.setPayType(1);
            order.setStatus(1);
            order.setPrice(reserveGoods.getTotalPrice());
            order.setPayBalances(deductBalance);
            order.setPayMgg(deductCoin);
            order.setExtraCost(0);
            order.setPayReady(order.getPrice() - order.getPayBalances());
            order.setRemark(null);
            orderService.save(order);

            // 订单商品
            orderGoods = new OrderGoods();
            orderGoods.setOrderId(order.getOrderId());
            orderGoods.setUserId(order.getUserId());
            orderGoods.setStoreId(order.getOrderId());
            orderGoods.setGoodsId(reserveGoods.getGoodsId());
            orderGoods.setGoodsSpecificationId(reserveGoods.getGoodsSpecificationId());
            orderGoods.setGoodsName(reserveGoods.getGoodsName());
            orderGoods.setSpecificationName(reserveGoods.getSpecificationName());
            orderGoods.setGoodsPic(reserveGoods.getGoodsPic());
            orderGoods.setGoodsPrice(reserveGoods.getGoodsPrice());
            orderGoods.setAmount(reserveGoods.getAmount());
            orderGoods.setProfit(0);
            ResultBody<GoodsSpecification> resGoodsSpecification = goodsSpecificationServiceClient.infoGoodsSpecification(reserveGoods.getGoodsSpecificationId());
            if(resGoodsSpecification != null && resGoodsSpecification.getCode() == ResultEnum.OK.getCode()) {
                orderGoods.setCoin(resGoodsSpecification.getData().getCoin());
            } else {
                orderGoods.setCoin(0);
            }
            orderGoods.setPostagePrice(0); // 没有邮费
            orderGoods.setTotalPrice(reserveGoods.getTotalPrice());
            orderGoods.setSold(0);
            //不激活权益
            orderGoods.setRemainWriteOffTimes(0);
            orderGoods.setIsPerennial(1);
            orderGoodsService.save(orderGoods);

            reserveOrder = new ReserveOrder();
            reserveOrder.setOrderId(order.getOrderId());
            reserveOrder.setReserveId(reserveId);
            reserveOrderService.save(reserveOrder);
        } else {
            order = orderService.getById(reserveOrder.getOrderId());
        }

        if(order == null) {
            log.info("xiaoc>> 获取订单信息失败，reserveId: {}", reserveId);
            return ResultBodyUtils.failedMsg("获取订单信息失败");
        }

        // 创建支付信息
        if (order.getPayReady() > 0) {
            String[] arrUsername = securityUserDetails.getUsername().split(":"); // username格式为：公众号appid:openid

            ResultBody<PayInfoVO> retPayInfoVO = yunStPaymentServiceClient.consumeApply(securityUserDetails.getUserId(),
                    order.getOrderId(), order.getPayReady(), YunstConstants.PAY_METHOD_WEIXIN, arrUsername[1], 24 * 60 * 60);
            PayInfoVO payInfoVO = retPayInfoVO.getData();
            if(payInfoVO != null) { //返回支付单号和实际支付金额
                payInfoVO.setOrderId(order.getOrderId());
                payInfoVO.setPayReady(order.getPayReady());
            }
            return retPayInfoVO;
        } else {
            List<OrderGoods> orderGoodsList = null;
            if(orderGoods != null) {
                orderGoodsList = Lists.newArrayList();
                orderGoodsList.add(orderGoods);
            } else {
                QueryWrapper<OrderGoods> queryWrapper = new QueryWrapper();
                queryWrapper.eq("order_id", order.getOrderId());
                queryWrapper.eq("user_id", order.getUserId());
                orderGoodsList = orderGoodsService.list(queryWrapper);
            }

            // 处理订单全余额购买
            order.setStatus(4);
            orderPaySuccess(order, orderGoodsList, securityUserDetails);
            //处理排号单
            Reserve reserve = new Reserve();
            reserve.setReserveId(reserveId);
            reserve.setStatus(5);
            if(reserveService.updateById(reserve)){
                Reserve reserve1 = reserveService.getById(reserveId);
                //通知任务
                reserveService.noticeReserve(reserve1.getStoreId());
            }
            //返回支付单号和实际支付金额
            PayInfoVO payInfoVO = new PayInfoVO();
            payInfoVO.setOrderId(order.getOrderId());
            payInfoVO.setPayReady(order.getPayReady());
            return ResultBodyUtils.ok(payInfoVO);
        }
    }

    /**
     * 处理订单全余额购买
     * @param orderr
     * @param orderGoodsList
     */
    private void  orderPaySuccess(Orderr orderr,List<OrderGoods> orderGoodsList,SecurityUserDetails securityUserDetails){
        String openId = ""; //openid
        String unionid = ""; //unionid
        String nickname = ""; //昵称
        String headimgurl = ""; //头像
        String phone = ""; //手机号码
        ReserveOrder reserveOrder = getReserveOrder(orderr.getOrderId());
        int orderStatus = 2;
        if(orderr.getStatus()==4 || reserveOrder!=null)orderStatus = 4;
        if(orderr.getCashierId()!=null)orderStatus = 4;
        if(orderr!=null){
            phone = orderr.getPhone();//获取订单的手机号
            UpdateWrapper<Orderr> orderrUpdateWrapper = new UpdateWrapper<>();
            orderrUpdateWrapper.eq("order_id",orderr.getOrderId());
            Orderr orderr1 = new Orderr();
            orderr1.setStatus(orderStatus);//已支付
            orderr1.setShutTime(new Date());//支付时间
            if(orderStatus==4)orderr1.setWritOffTime(new Date());//已核销
            orderService.update(orderr1,orderrUpdateWrapper);
        }
        //更新分销数据
        retailOrderServiceClient.updateRetailOrder(orderr.getOrderId(), RetailConstants.RETAIL_ORDER_PREWRITE);//已支付
        //查询会员信息
        ResultBody<BaseUser> baseUserResultBody = baseUserServiceClient.infoBaseUser(orderr.getUserId());
        if(baseUserResultBody!=null && baseUserResultBody.getCode() == ResultEnum.OK.getCode()){
            BaseUser baseUser = baseUserResultBody.getData();
            String[] nicknames = baseUser.getNickName().split(":");
            if(nicknames.length>=2){
                openId = nicknames[1];
            }
        }
        if(openId!=""){
            ResultBody<MpweixinUser> mpweixinUserResultBody = mpweixinServiceClient.selectMpUserInfo(openId);
            if(mpweixinUserResultBody != null && mpweixinUserResultBody.getCode() == ResultEnum.OK.getCode()){
                MpweixinUser mpweixinUser = mpweixinUserResultBody.getData();
                if(mpweixinUser!=null){
                    unionid = mpweixinUser.getUnionid();
                }
            }
        }
        //获取用户信息
        String[] arrUsername = securityUserDetails.getUsername().split(":");
        if(arrUsername.length>=2){
            ResultBody<MpweixinUserExpand> mpweixinUserExpandResultBody = mpweixinServiceClient.selectUserInfo(orderr.getUserId(),arrUsername[1]);
            if(mpweixinUserExpandResultBody!=null && mpweixinUserExpandResultBody.getCode() == ResultEnum.OK.getCode()){
                MpweixinUserExpand mpweixinUserExpand = mpweixinUserExpandResultBody.getData();
                if(mpweixinUserExpand!=null){
                    nickname = mpweixinUserExpand.getNickname();
                    headimgurl = mpweixinUserExpand.getHeadimgurl();
                    if(orderr!=null){
                        UpdateWrapper<Orderr> orderrUpdateWrapper = new UpdateWrapper<>();
                        orderrUpdateWrapper.eq("order_id",orderr.getOrderId());
                        Orderr orderr1 = new Orderr();
                        orderr1.setReceiverHeadimgurl(headimgurl);
                        orderService.update(orderr1,orderrUpdateWrapper);
                    }
                }
            }
        }
        if(unionid!=""){
            //加入会员统计表
            orderStats1Service.createOrUpdate(unionid,orderr.getUserId(),orderr.getStoreId(),
                    nickname,headimgurl,phone,orderr.getPrice(),orderr.getPrice());
        }
        //更新订单商品数据
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("order_id",orderr.getOrderId());
        orderGoodsQueryWrapper.eq("sold",0);
        if(orderGoodsList!=null && orderGoodsList.size()>0){
            UpdateWrapper<OrderGoods> orderGoodsUpdateWrapper = new UpdateWrapper<>();
            orderGoodsUpdateWrapper.eq("order_id",orderr.getOrderId());
            OrderGoods orderGoods1 = new OrderGoods();
            orderGoods1.setSold(1);//已出售
            orderGoodsService.update(orderGoods1,orderGoodsUpdateWrapper);
            //查询核销人信息
            Map<String,Object> writeOffMap = getWriteInfomation(orderr,reserveOrder);
            Long writeOffUserId = null;
            String writeOffUserName = null;
            if(writeOffMap.get("writeOffUserId")!=null){
                writeOffUserId = Long.valueOf(writeOffMap.get("writeOffUserId").toString());
                writeOffUserName = writeOffMap.get("writeOffUserName").toString();
            }
            //更新销量
            for(OrderGoods orderGoods:orderGoodsList){
                //更新指定谁的权限
                UpdateWrapper<OrderGoods> orderGoodsUpdateWrapper2 = new UpdateWrapper<>();
                orderGoodsUpdateWrapper2.eq("order_goods_id",orderGoods.getOrderGoodsId());
                OrderGoods orderGoods2 = new OrderGoods();
                orderGoods2.setUserId(orderr.getUserId());
                if(orderStatus==2) orderGoods2.setRemainWriteOffTimes(orderGoods.getAmount());
                orderGoodsService.update(orderGoods2,orderGoodsUpdateWrapper2);
                goodsSpecificationServiceClient.updateSalesVolume(orderGoods.getGoodsSpecificationId(),orderGoods.getAmount());
                if(orderStatus==4){
                    List<OrderWriteOffLog> orderWriteOffLogList = new LinkedList<>();
                    for(int i=0;i<orderGoods.getAmount();i++){
                        OrderWriteOffLog orderWriteOffLog = new OrderWriteOffLog();
                        orderWriteOffLog.setOrderId(orderGoods.getOrderId());
                        orderWriteOffLog.setOrderGoodsId(orderGoods.getOrderGoodsId());
                        if(orderr.getPayType()==1 && orderr.getCashierId()!=null){
                            orderWriteOffLog.setPayType(4);//微信收银
                        }else{
                            orderWriteOffLog.setPayType(orderr.getPayType());
                        }
                        orderWriteOffLog.setPrice(orderGoods.getGoodsPrice());
                        orderWriteOffLog.setReceiver(orderr.getReceiver()==null?nickname:orderr.getReceiver());
                        orderWriteOffLog.setReceiverHeadimgurl(orderr.getReceiverHeadimgurl()==null?headimgurl:orderr.getReceiverHeadimgurl());
                        orderWriteOffLog.setStoreId(orderr.getStoreId());
                        if(orderr.getCashierId()==null){
                            orderWriteOffLog.setUserId(writeOffUserId);
                            orderWriteOffLog.setUserName(writeOffUserName);
                        }else {
                            orderWriteOffLog.setUserId(orderr.getCashierId());
                            orderWriteOffLog.setUserName(orderr.getCashierName());
                        }
                        orderWriteOffLogList.add(orderWriteOffLog);
                    }
                    //插入核销表
                    orderWriteOffLogService.saveBatch(orderWriteOffLogList);
                }
            }
        }
        if(orderStatus == 4 && orderr.getPayType() == 1){
            if(orderr.getExtraCost()!=null && orderr.getExtraCost()>0){
                //查询核销人
                Map<String,Object> writeOffMap = getWriteInfomation(orderr,reserveOrder);
                Long writeOffUserId = null;
                String writeOffUserName = null;
                if(writeOffMap.get("writeOffUserId")!=null){
                    writeOffUserId = Long.valueOf(writeOffMap.get("writeOffUserId").toString());
                    writeOffUserName = writeOffMap.get("writeOffUserName").toString();
                }
                //插入核销记录
                OrderWriteOffLog orderWriteOffLog = new OrderWriteOffLog();
                orderWriteOffLog.setOrderId(orderr.getOrderId());
                orderWriteOffLog.setOrderGoodsId(orderr.getOrderId());
                if(orderr.getPayType()==1 && orderr.getCashierId()!=null){
                    orderWriteOffLog.setPayType(4);//微信收银
                }else{
                    orderWriteOffLog.setPayType(orderr.getPayType());
                }
                orderWriteOffLog.setPrice(orderr.getExtraCost());
                orderWriteOffLog.setReceiver(orderr.getReceiver()==null?nickname:orderr.getReceiver());
                orderWriteOffLog.setReceiverHeadimgurl(orderr.getReceiverHeadimgurl()==null?headimgurl:orderr.getReceiverHeadimgurl());
                orderWriteOffLog.setStoreId(orderr.getStoreId());
                if(writeOffUserId!=null){
                    orderWriteOffLog.setUserId(writeOffUserId);
                    orderWriteOffLog.setUserName(writeOffUserName);
                }else {
                    orderWriteOffLog.setUserId(orderr.getCashierId());
                    orderWriteOffLog.setUserName(orderr.getCashierName());
                }
                //插入核销表
                orderWriteOffLogService.save(orderWriteOffLog);
            }
            //更新订单统计
            orderStats2Service.createOrUpdate(orderr, 0, 1);
            //分销费用
            int shareAmount = 0;
            //门店获得资金
            int amount = orderr.getPrice();
            //手续费=订单总金额*6/1000;
            int fees = orderr.getPrice()*6/1000;
            ResultBody<RetailOrder> retailOrderResultBody = retailOrderServiceClient.getRetailOrder(orderr.getOrderId());
            if(retailOrderResultBody!=null && retailOrderResultBody.getCode() == ResultEnum.OK.getCode()){
                RetailOrder retailOrder = retailOrderResultBody.getData();
                if(retailOrder!=null){
                    shareAmount = retailOrder.getProfit()==null?0:retailOrder.getProfit();
                    int price = orderr.getPrice()==null?0:retailOrder.getProfit();
                    int profit = retailOrder.getProfit()==null?0:retailOrder.getProfit();
                    amount = price - profit;
                }
            }
            log.info(">> minjie 核算后的门店资金：{}，分销费用：{}，手续费：{}",amount,shareAmount,fees);
            //处理流水
            String des = "无需核销的资金记录";
            storeFlowServiceClient.saveStoreFlow(orderr.getStoreId(),amount,shareAmount,fees,
                    1, orderr.getOrderId(),des,Integer.valueOf(DateUtils.formatYear()),
                    Integer.valueOf(DateUtils.formatMonth()),Integer.valueOf(DateUtils.formatDay()));
            //更新门店资金
            ResultBody<Store> retStrore = storeServiceClient.updateStoreBalance(orderr.getStoreId(),amount);
            if(retStrore.getCode() != ResultEnum.OK.getCode()){
                log.info(">>minjie 更新门店资金出错,storeId:{},balance:{}",orderr.getStoreId(),orderr.getPrice());
            }
        }
        //直接更新用户分享得到的钱
        if(orderr.getActType()!=null && orderr.getActType().equals(2)){
            retailOrderServiceClient.updateRetailOrder(orderr.getOrderId(),4);
        }
        //加上余额明细
        mpweixinServiceClient.saveFlow(orderr.getOrderId(),orderr.getUserId(),orderr.getPayBalances(),3);
    }

    /**
     * 查询核销人
     * @return
     */
    private Map<String,Object> getWriteInfomation(Orderr orderr,ReserveOrder reserveOrder){
        Map<String,Object> resultMap = Maps.newHashMap();
        //查询核销人
        Long writeOffUserId = null;
        String writeOffUserName = null;
        if(reserveOrder!=null){
            //查询排队单
            Reserve reserve = reserveService.getById(reserveOrder.getReserveId());
            ResultBody<StoreStaff> storeStaffResultBody = storeStaffServiceClient.selectStoreStaff(orderr.getStoreId(),reserve.getStaffId(),null);
            if(storeStaffResultBody!=null && storeStaffResultBody.getCode()==ResultEnum.OK.getCode()){
                StoreStaff storeStaff = storeStaffResultBody.getData();
                if(storeStaff!=null){
                    writeOffUserId = storeStaff.getUserId();
                    writeOffUserName = storeStaff.getName();
                }
            }
        }else if(orderr.getCashierId()==null){
            ResultBody<StoreStaff> storeStaffResultBody = storeStaffServiceClient.selectStoreStaff(orderr.getStoreId(),null,"MERCHANT");
            if(storeStaffResultBody!=null && storeStaffResultBody.getCode()==ResultEnum.OK.getCode()){
                StoreStaff storeStaff = storeStaffResultBody.getData();
                if(storeStaff!=null){
                    writeOffUserId = storeStaff.getUserId();
                    writeOffUserName = storeStaff.getName();
                }
            }
        }
        resultMap.put("writeOffUserId",writeOffUserId);
        resultMap.put("writeOffUserName",writeOffUserName);
        return resultMap;
    }

    /**
     * 查询订单是否关联预约单
     * @param orderId
     * @return
     */
    private ReserveOrder getReserveOrder(long orderId){
        QueryWrapper<ReserveOrder> reserveOrderQueryWrapper = new QueryWrapper<>();
        reserveOrderQueryWrapper.eq("order_id",orderId);
        reserveOrderQueryWrapper.orderByDesc("ct");
        reserveOrderQueryWrapper.last("LIMIT 1");
        ReserveOrder reserveOrder = reserveOrderService.getOne(reserveOrderQueryWrapper);
        return reserveOrder;
    }

    /**
     * 收银创建订单
     * @param trolleyList //规格列表,{[“goodsSpecificationId”:1312,"amount":14],[“goodsSpecificationId”:1565,"amount":14]}
     * @param extraCost //其他项目费用
     * @param payType //支付方式，1微信，2现金，3刷卡
     * @return
     */
    @PostMapping("createcashregister")
    public ResultBody createcashregister(
            @RequestParam(value = "storeId", required = false) Long storeId,
            @RequestParam(value = "trolleyList", required = false) String trolleyList,
            @RequestParam(value = "extraCost", required = false, defaultValue = "0") int extraCost,
            @RequestParam(value = "payType", required = false, defaultValue = "1") int payType,
            @RequestParam(value = "remark", required = false) String remark) {
        // 获取当前用户信息
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        long userId = securityUserDetails.getUserId();
        //获取购物车列表
        List<GoodsSpecList> goodsSpecListList = getGoodsSpecList(null, trolleyList);
        Orderr order = new Orderr();//订单信息
        int price = 0;//订单金额
        int sold = 0;//没有销售状态
        int status = OrderConstants.ORDER_STATUS_PREPAY;//订单初始状态--待支付
        if(storeId==null)storeId = 0L;
        if(goodsSpecListList!=null && goodsSpecListList.size()>0){
            for (GoodsSpecList goodsSpecList : goodsSpecListList) {
                price = price + goodsSpecList.getPrice() * goodsSpecList.getAmount();
                if(storeId <= 0) {
                    storeId = goodsSpecList.getStoreId();
                }
            }
        }
        //查询员工账号
        ResultBody<StoreStaff> storeStaffResultBody = storeStaffServiceClient.selectStoreStaff(storeId,userId,null);
        StoreStaff storeStaff = null;
        if(storeStaffResultBody.getCode() == ResultEnum.OK.getCode()){
            storeStaff = storeStaffResultBody.getData();
        }
        if(storeStaff==null)return ResultBodyUtils.failed("员工账号出错！");
        //加上额外消费
        price = price + extraCost;
        if (payType != 1) {
            sold = 1;
            status = OrderConstants.ORDER_STATUS_COMPLETED;
        }
        //扣减普通商品库存
        if(goodsSpecListList!=null && goodsSpecListList.size()>0){
            for (GoodsSpecList goodsSpecList : goodsSpecListList) {
                ResultBody retUpdateStockQty = goodsSpecificationServiceClient.updateStockQty(goodsSpecList.getSpecId(), -goodsSpecList.getAmount());
                if (retUpdateStockQty.getCode() != ResultEnum.OK.getCode()) {
                    return retUpdateStockQty;
                }
            }
        }
        // 创建订单
        order.setStoreId(storeId);
        order.setNumber(UUID.randomUUID().toString().replaceAll("-", ""));
        order.setStatus(status);
        order.setPrice(price);
        order.setPayBalances(0);
        order.setPayMgg(0);
        order.setExtraCost(extraCost);
        order.setPayReady(price);
        order.setPayType(payType);
        order.setCashierId(userId);
        order.setCashierName(storeStaff.getName());
        order.setRemark(remark);
        if(orderService.save(order) && order.getPayType()!=1){
            //添加门店业绩
            orderStats2Service.createOrUpdate(order,0,0);
        }
        // 创建订单商品信息
        List<OrderGoods> orderGoodsList = saveBatchOrderGoods(order.getOrderId(),null,goodsSpecListList, sold, null);
        if(status==4){//如果是线下收银则需要添加核销信息
            log.info(">>minjie 添加核销的信息:"+JsonUtils.Obj2Str(goodsSpecListList));
            if(orderGoodsList!=null && orderGoodsList.size()>0){
                List<OrderWriteOffLog> orderWriteOffLogList = new LinkedList<>();
                for(OrderGoods orderGoods : orderGoodsList){
                    for(int i=0;i<orderGoods.getAmount();i++){
                        OrderWriteOffLog orderWriteOffLog = new OrderWriteOffLog();
                        orderWriteOffLog.setOrderId(order.getOrderId());
                        orderWriteOffLog.setOrderGoodsId(orderGoods.getOrderGoodsId());
                        if(order.getPayType()==1 && order.getCashierId()!=null){
                            orderWriteOffLog.setPayType(4);//微信收银
                        }else{
                            orderWriteOffLog.setPayType(order.getPayType());
                        }
                        orderWriteOffLog.setPrice(orderGoods.getGoodsPrice());
                        orderWriteOffLog.setReceiver(order.getReceiver());
                        orderWriteOffLog.setReceiverHeadimgurl(order.getReceiverHeadimgurl());
                        orderWriteOffLog.setStoreId(order.getStoreId());
                        orderWriteOffLog.setUserId(userId);
                        orderWriteOffLog.setUserName(securityUserDetails.getUsername());
                        orderWriteOffLogList.add(orderWriteOffLog);
                    }
                }
                //插入核销表
                orderWriteOffLogService.saveBatch(orderWriteOffLogList);
            }
            if(extraCost!=0 && payType != 1){
                OrderWriteOffLog orderWriteOffLog = new OrderWriteOffLog();
                orderWriteOffLog.setOrderId(order.getOrderId());
                orderWriteOffLog.setOrderGoodsId(order.getOrderId());
                if(order.getPayType()==1 && order.getCashierId()!=null){
                    orderWriteOffLog.setPayType(4);//微信收银
                }else{
                    orderWriteOffLog.setPayType(order.getPayType());
                }
                orderWriteOffLog.setPrice(extraCost);
                orderWriteOffLog.setReceiver(order.getReceiver());
                orderWriteOffLog.setReceiverHeadimgurl(order.getReceiverHeadimgurl());
                orderWriteOffLog.setStoreId(order.getStoreId());
                orderWriteOffLog.setUserId(userId);
                orderWriteOffLog.setUserName(securityUserDetails.getUsername());
                orderWriteOffLogService.save(orderWriteOffLog);
            }
        }
        return ResultBodyUtils.ok(order);
    }

    /**
     * 批量添加订单商品
     * @param orderId
     * @param goodsSpecListList
     * @param sold 出售状态，0没有出售1已出售
     * @param act
     */
    private List<OrderGoods> saveBatchOrderGoods(long orderId, Long userId, List<GoodsSpecList>  goodsSpecListList,
                                                 int sold, Act act) {
        if(goodsSpecListList!=null && goodsSpecListList.size()>0){
            List<OrderGoods> listOrderGoods = new LinkedList<>();
            for (GoodsSpecList goodsSpecList : goodsSpecListList) {
                OrderGoods orderGoods = new OrderGoods();
                orderGoods.setOrderId(orderId);
                orderGoods.setUserId(userId);
                orderGoods.setStoreId(goodsSpecList.getStoreId());
                orderGoods.setGoodsId(goodsSpecList.getGoodsId());
                orderGoods.setGoodsSpecificationId(goodsSpecList.getSpecId());
                orderGoods.setGoodsName(goodsSpecList.getGoodsName());
                orderGoods.setSpecificationName(goodsSpecList.getSpecName());
                orderGoods.setGoodsPic(goodsSpecList.getGoodsPic());
                orderGoods.setGoodsPrice(goodsSpecList.getPrice());
                orderGoods.setAmount(goodsSpecList.getAmount());
                orderGoods.setProfit(goodsSpecList.getProfit());
                orderGoods.setCoin(goodsSpecList.getCoin());
                orderGoods.setPostagePrice(0); // 没有邮费
                orderGoods.setTotalPrice(goodsSpecList.getPrice() * goodsSpecList.getAmount());
                orderGoods.setSold(sold);
                //不激活权益
                orderGoods.setRemainWriteOffTimes(0);
                orderGoods.setDes(goodsSpecList.getDesc());

                if (act != null) {//如何是活动订单，查看核销有效期
                    orderGoods.setDes(act.getDes());//使用规则
                    if (act.getEffectiveType().equals(0)) {//指定日期，直接赋值
                        orderGoods.setIsPerennial(0);
                        orderGoods.setCodeStime(act.getCodeStime());
                        orderGoods.setCodeEtime(act.getCodeEtime());
                    }
                    if (act.getEffectiveType().equals(1)) {//固定有效天数
                        orderGoods.setIsPerennial(0);
                        orderGoods.setCodeStime(new Date());
                        orderGoods.setCodeEtime(DateUtils.getAfterDayDate(act.getEffectiveDay()));
                    }
                    if (act.getEffectiveType().equals(2)) {//长期有效
                        orderGoods.setIsPerennial(1);
                    }
                } else {
                    orderGoods.setIsPerennial(1);
                }
                listOrderGoods.add(orderGoods);
            }
            if(listOrderGoods.size() > 0) {
                if(orderGoodsService.saveBatch(listOrderGoods))
                    return listOrderGoods;
            }
        }
        return null;
    }

    /**
     * 收银列表
     * @param page
     * @param limit
     * @param storeId
     * @return
     */
    @PostMapping("listcashregister")
    public ResultBody listcashregister(@RequestParam(value = "page",defaultValue = "1") int page,
                           @RequestParam(value = "limit",defaultValue = "5") int limit,
                           @RequestParam(value = "storeId") long storeId) {
        // 查询条件
        CriteriaQuery criteriaQuery = new CriteriaQuery(new PageParams(page, limit));
        criteriaQuery.select("count(*) count", "sum(price) price", "DATE_FORMAT(ct,'%Y-%m-%d') date");
        criteriaQuery.eq("store_id", storeId);
        criteriaQuery.eq("status",4);
        criteriaQuery.gt("cashier_id", 0); // 存在收银的即为收银订单
        criteriaQuery.groupBy("DATE_FORMAT(ct,'%Y%m%d')");
        criteriaQuery.orderByDesc("DATE_FORMAT(ct,'%Y%m%d')");

        IPage<Map<String, Object>> pageList = orderService.pageList(criteriaQuery);
        if(pageList.getRecords() != null && pageList.getRecords().size() > 0) {
            // 循环获取详细信息
            for(Map<String, Object> itemMap : pageList.getRecords()) {
                QueryWrapper<Orderr> queryWrapper = new QueryWrapper();
                queryWrapper.eq("store_id", storeId);
                queryWrapper.eq("status",4);
                queryWrapper.gt("cashier_id", 0); // 存在收银的即为收银订单
                queryWrapper.ge("ct", itemMap.get("date"));
                queryWrapper.le("ct", itemMap.get("date") + " 23:59:59");
                queryWrapper.orderByDesc("ct");
                itemMap.put("listOrder", orderService.list(queryWrapper));
            }
        }
        return ResultBodyUtils.ok(pageList);
    }

    /**
     * 订单列表
     * @param page
     * @param limit
     * @param userId //指定用户查询订单
     * @param storeId //门店订单
     * @param keyword //模糊查询收货人
     * @param status
     * @return
     */
    @PostMapping("list")
    public ResultBody list(@RequestParam(value = "page",defaultValue = "1") int page,
                           @RequestParam(value = "limit",defaultValue = "10") int limit,
                           @RequestParam(value = "userId",required = false) Long userId,
                           @RequestParam(value = "storeId",required = false) Long storeId,
                           @RequestParam(value = "keyword",required = false) String keyword,
                           @RequestParam(value = "status",defaultValue = "-1") int status) {
        //返回的分页类型
        IPage<OrderList> orderListIPage = new Page<>();
        // 获取当前用户信息
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        IPage<Orderr> orderrIPage = null;
        //C端用户查询订单
        QueryWrapper<Orderr> orderrQueryWrapper = new QueryWrapper<>();
        if(status != -1){
            if(status==0){
                List<Long> statusList = new ArrayList<>();
                statusList.add(0L);
                statusList.add(6L);
                orderrQueryWrapper.in("status",statusList);
            }else{
                orderrQueryWrapper.eq("status",status);
            }
        }
        if(storeId==null){
            orderrQueryWrapper.eq("user_id",securityUserDetails.getUserId());
            orderrQueryWrapper.orderByDesc("ct");
            orderrIPage = orderService.page(new Page<Orderr>(page,limit),orderrQueryWrapper);
        }else{
            //B端门店查询订单
            if(StringUtils.isNotEmpty(keyword)){
                orderrQueryWrapper.and(Wrapper->Wrapper.like("phone",keyword).or().like("receiver",keyword));
            }
            if(userId != null) orderrQueryWrapper.eq("user_id",userId);
            orderrQueryWrapper.eq("store_id",storeId);
            orderrQueryWrapper.orderByDesc("ct");
            orderrIPage = orderService.page(new Page<Orderr>(page,limit),orderrQueryWrapper);
        }
        orderListIPage.setCurrent(orderrIPage.getCurrent());
        orderListIPage.setPages(orderrIPage.getPages());
        orderListIPage.setSize(orderrIPage.getSize());
        orderListIPage.setTotal(orderrIPage.getTotal());
        List<OrderList> orderListList = new ArrayList<>();
        if(orderrIPage.getRecords().size()>0){
            for (Orderr orderr : orderrIPage.getRecords()) {
                OrderList orderList = new OrderList();
                orderList.setStatus(orderr.getStatus());
                orderList.setTotalPrice(orderr.getPrice());
                orderList.setCashierId(orderr.getCashierId()==null?0:orderr.getCashierId());
                orderList.setOrderId(orderr.getOrderId());
                // 获取订单详细信息
                QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
                orderGoodsQueryWrapper.eq("order_id",orderr.getOrderId());
                List<OrderGoods> orderGoodsList = orderGoodsService.list(orderGoodsQueryWrapper);
                //取第一个商品
                if(orderGoodsList!=null && orderGoodsList.size()>0){
                    int totalAmount = 0;
                    for(OrderGoods orderGoods:orderGoodsList){
                        totalAmount = totalAmount + orderGoods.getAmount();
                    }
                    //如果有其他服务也算一个商品
                    if(orderr.getExtraCost()!=null && orderr.getExtraCost()>0){
                        totalAmount = totalAmount + 1;
                    }
                    orderList.setTotalAmount(totalAmount);
                    orderList.setAmount(orderGoodsList.get(0).getAmount());
                    orderList.setGoodsName(orderGoodsList.get(0).getGoodsName());
                    orderList.setGoodsPic(orderGoodsList.get(0).getGoodsPic());
                    orderList.setGoodsPrice(orderGoodsList.get(0).getGoodsPrice());
                    orderList.setSpecificationName(orderGoodsList.get(0).getSpecificationName());
                }else {
                    orderList.setAmount(1);
                    orderList.setTotalAmount(1);
                    orderList.setGoodsName(OrderListConstants.goodsName);
                    orderList.setGoodsPic(OrderListConstants.goodsPic);
                    orderList.setGoodsPrice(orderr.getPrice());
                    orderList.setSpecificationName(OrderListConstants.specificationName);
                }
                if(storeId!=null){//门店订单列表的信息
                    orderList.setReceiver(orderr.getReceiver());
                    orderList.setCt(orderr.getCt());
                    //拨号记录
                    List<ContactList> contactLists = new ArrayList<>();
                    QueryWrapper<OrderContactLog> contactLogQueryWrapper = new QueryWrapper<>();
                    contactLogQueryWrapper.eq("order_id",orderr.getOrderId());
                    contactLogQueryWrapper.orderByDesc("ct");
                    List<OrderContactLog> orderContactLogList = orderContactLogService.list(contactLogQueryWrapper);
                    orderList.setContactTimes(orderContactLogList.size()>3?3:orderContactLogList.size());
                    if(orderContactLogList.size()>0){
                        OK:for(int i=0;i<orderContactLogList.size();i++){
                            ContactList contactList = new ContactList();
                            contactList.setStoreStaffName(orderContactLogList.get(i).getStaffName());
                            contactList.setCt(orderContactLogList.get(i).ct);
                            contactLists.add(contactList);
                            if(i==2){
                                break OK;
                            }
                        }
                    }
                    orderList.setContactList(contactLists);
                }else{
                    //查询门店
                    ResultBody<Store> storeResultBody = storeServiceClient.getStore(orderr.getStoreId());
                    if(storeResultBody!=null && storeResultBody.getCode() == ResultEnum.OK.getCode()){
                        Store store = storeResultBody.getData();
                        if(store!=null)orderList.setStoreName(store.getName());
                    }
                }
                orderListList.add(orderList);
            }
        }
        orderListIPage.setRecords(orderListList);
        return ResultBodyUtils.ok(orderListIPage);
    }


    /**
     * 后台获取订单列表
     * @param page
     * @param limit
     * @param storeId
     * @param keyword
     * @return
     */
    @PostMapping("listbycondition")
    public ResultBody listbycondition(@RequestParam(value = "page",defaultValue = "1") int page,
                           @RequestParam(value = "limit",defaultValue = "10") int limit,
                           @RequestParam(value = "storeId",required = false) Long storeId,
                           @RequestParam(value = "keyword",required = false) String keyword){
        QueryWrapper<Orderr> orderrQueryWrapper = new QueryWrapper<>();
        orderrQueryWrapper.eq("store_id",storeId);
        orderrQueryWrapper.like("order_id",keyword);
        orderrQueryWrapper.orderByDesc("ct");
        IPage<Orderr> orderrIPage = orderService.page(new Page<>(page,limit),orderrQueryWrapper);
        return ResultBodyUtils.ok(orderrIPage);
    }

    /**
     * 门店资金账户
     * @param page
     * @param limit
     * @param storeId
     * @param dayMonthYear
     * @return
     */
    @PostMapping("liststoreflow")
    public ResultBody liststoreflow(@RequestParam(value = "page",defaultValue = "1") int page,
                           @RequestParam(value = "limit",defaultValue = "30") int limit,
                           @RequestParam(value = "storeId") Long storeId,
                           @RequestParam("dayMonthYear") String dayMonthYear) {
        //返回的分页类型
        IPage<OrderList> orderListIPage = new Page<>();
        List<Long> orderIds = new ArrayList<>();
        QueryWrapper<Orderr> orderrQueryWrapper = new QueryWrapper<>();
        orderrQueryWrapper.in("store_id", storeId);
        orderrQueryWrapper.eq("status", 4);
        orderrQueryWrapper.ge("writ_off_time",dayMonthYear+" 00:00:00");
        orderrQueryWrapper.le("writ_off_time",dayMonthYear+" 23:59:59");
        orderrQueryWrapper.orderByDesc("writ_off_time");
        IPage<Orderr> orderrIPage =  orderService.page(new Page<Orderr>(page,limit),orderrQueryWrapper);
        orderListIPage.setCurrent(orderrIPage.getCurrent());
        orderListIPage.setPages(orderrIPage.getPages());
        orderListIPage.setSize(orderrIPage.getSize());
        orderListIPage.setTotal(orderrIPage.getTotal());
        List<OrderList> orderListList = new ArrayList<>();
        if(orderrIPage.getTotal()>0) {
            for (Orderr orderr : orderrIPage.getRecords()) {
                OrderList orderList = new OrderList();
                // 获取订单详细信息
                QueryWrapper<OrderGoods> orderGoodsQueryWrapper2 = new QueryWrapper<>();
                orderGoodsQueryWrapper2.eq("order_id", orderr.getOrderId());
                List<OrderGoods> orderGoodsList1 = orderGoodsService.list(orderGoodsQueryWrapper2);
                //取第一个商品
                if (orderGoodsList1.size() > 0) {
                    orderList.setAmount(orderGoodsList1.get(0).getAmount());
                    orderList.setGoodsName(orderGoodsList1.get(0).getGoodsName());
                    orderList.setGoodsPic(orderGoodsList1.get(0).getGoodsPic());
                    orderList.setGoodsPrice(orderGoodsList1.get(0).getGoodsPrice());
                    orderList.setSpecificationName(orderGoodsList1.get(0).getSpecificationName());
                }else {
                    orderList.setAmount(1);
                    orderList.setTotalAmount(1);
                    orderList.setGoodsName(OrderListConstants.goodsName);
                    orderList.setGoodsPic(OrderListConstants.goodsPic);
                    orderList.setGoodsPrice(orderr.getExtraCost());
                    orderList.setSpecificationName(OrderListConstants.specificationName);
                }
                orderList.setOrderId(orderr.getOrderId());
                orderList.setTotalPrice(orderr.getPrice());
                orderList.setCt(orderr.getWritOffTime());
                orderListList.add(orderList);
            }
        }
        orderListIPage.setRecords(orderListList);
        return ResultBodyUtils.ok(orderListIPage);
    }

    /**
     * 门店资金核算
     * @param storeId
     * @param dayMonthYear
     * @return
     */
    @PostMapping("liststoreflowinfo")
    public ResultBody liststoreflowinfo(
                @RequestParam(value = "storeId",required = false) Long storeId,
                @RequestParam("dayMonthYear") String dayMonthYear) {
        OrderStoreFlowInfo orderStoreFlowInfo = new OrderStoreFlowInfo();
        //查询当天核销的订单
        QueryWrapper<Orderr> orderrQueryWrapper = new QueryWrapper<>();
        orderrQueryWrapper.in("store_id", storeId);
        orderrQueryWrapper.eq("status", 4);
        orderrQueryWrapper.ge("writ_off_time",dayMonthYear+" 00:00:00");
        orderrQueryWrapper.le("writ_off_time",dayMonthYear+" 23:59:59");
        List<Orderr> orderrList = orderService.list(orderrQueryWrapper);
        int totalprice = 0;
        for(Orderr orderr:orderrList){
            totalprice = totalprice + orderr.getPrice();
        }
        orderStoreFlowInfo.setOrderPrice(totalprice);
        orderStoreFlowInfo.setOrderNumber(orderrList.size());
        return ResultBodyUtils.ok(orderStoreFlowInfo);
    }

    /**
     * 更新订单信息
     * @param orderId
     * @param receiver
     * @param phone
     * @return
     */
    @PostMapping("update")
    public ResultBody update(@RequestParam("orderId") long orderId,
                             @RequestParam(value = "receiver", required = false) String receiver,
                             @RequestParam(value = "phone", required = false) String phone) {
        Orderr order = orderService.getById(orderId);
        if (order == null) {
            log.error("xiaoc>> 更新订单详情失败，orderId: {}", orderId);
            ResultBodyUtils.failed("订单不存在");
        }
        if(order.getStatus() != 1) { // 待支付状态
            log.error("xiaoc>> 非待支付状态不允许更改失败，orderId: {}", orderId);
            ResultBodyUtils.failed("当前状态不允许更改");
        }
        //用户信息
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        long userId = securityUserDetails.getUserId();
        if (!BaseConstants.ACCOUNT_DOMAIN_MP.equalsIgnoreCase(securityUserDetails.getDomain())) { // 是否C端登录
            log.error("xiaoc>> 非C端登录不允许更改失败，orderId: {}", orderId);
            ResultBodyUtils.failed("当前身份不允许更改");
        }
        int deductBalance = 0; // 余额扣费额度
        int deductCoin = 0; // 乖乖币扣费额度
        if(order.getPayMgg() <= 0 && order.getPayBalances() <= 0) {
            // 扣减用户钱包
            ResultBody<DeductUserAmount> deductUserAmountResultBody = mpweixinServiceClient.updateDeductAmount(securityUserDetails.getUserId(), order.getPrice(), 0);
            if (deductUserAmountResultBody.getCode() == ResultEnum.OK.getCode() && deductUserAmountResultBody.getData() != null) {
                DeductUserAmount deductUserAmount = deductUserAmountResultBody.getData();
                if (deductUserAmount != null) {
                    deductBalance = deductUserAmount.getDeductBalance();
                    deductCoin = deductUserAmount.getDeductCoin();
                }
            }
        }else{
            deductBalance = order.getPayBalances();
            deductCoin = order.getPayMgg();
        }

        // 更新联系人或电话
        Orderr orderUpdate = new Orderr();
        orderUpdate.setOrderId(orderId);
        orderUpdate.setUserId(userId);
        orderUpdate.setReceiver(receiver);
        orderUpdate.setPhone(phone);
        if(deductBalance >= 0) {
            orderUpdate.setPayBalances(deductBalance);
        }
        if(deductCoin >= 0) {
            orderUpdate.setPayMgg(deductCoin);
        }
        int payReady = order.getPrice() - orderUpdate.getPayBalances() - orderUpdate.getPayMgg();
        // 支付金额
        orderUpdate.setPayReady(payReady);
        orderService.updateById(orderUpdate);

        // 创建支付信息
        if (orderUpdate.getPayReady() > 0) {
            String[] arrUsername = securityUserDetails.getUsername().split(":"); // username格式为：公众号appid:openid
            if (arrUsername.length >= 2) {
                ResultBody<PayInfoVO> retPayInfoVO = yunStPaymentServiceClient.consumeApply(securityUserDetails.getUserId(),
                        order.getOrderId(), payReady, YunstConstants.PAY_METHOD_WEIXIN, arrUsername[1], OrderConstants.PAY_OUTTIME);
                PayInfoVO payInfoVO = retPayInfoVO.getData();
                if(payInfoVO!=null) {//返回支付单号和实际支付金额
                    payInfoVO.setOrderId(order.getOrderId());
                    payInfoVO.setPayReady(payReady);
                }
                return retPayInfoVO;
            } else {
                log.error("xiaoc>> 从缓存中获取微信用户openid失败，username: {}", securityUserDetails.getUsername());
            }
        } else if(orderUpdate.getPayReady()==0){
            // 处理订单全余额购买
            List<OrderGoods> orderGoodsList = orderGoodsService.listByOrderId(order.getOrderId(),null);
            if(order.getUserId()==null){
                order.setUserId(securityUserDetails.getUserId());
            }
            if(orderUpdate.getPayBalances()!=null)order.setPayBalances(orderUpdate.getPayBalances());
            if(orderUpdate.getPayMgg()!=null)order.setPayMgg(orderUpdate.getPayMgg());
            if(orderUpdate.getPayReady()!=null)order.setPayReady(orderUpdate.getPayReady());
            orderPaySuccess(order,orderGoodsList,securityUserDetails);
        }
        //返回支付单号和实际支付金额
        PayInfoVO payInfoVO = new PayInfoVO();
        payInfoVO.setOrderId(order.getOrderId());
        payInfoVO.setPayReady(payReady);
        return ResultBodyUtils.ok(payInfoVO);
    }

    /**
     * 获取订单详情
     *
     * @param orderId
     * @return
     */
    @PostMapping("info")
    public ResultBody info(@RequestParam("orderId") Long orderId) {
        //用户信息
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        long userId = securityUserDetails.getUserId().longValue();
        MpweixinUserExpand mpweixinUserExpand = null;
        String openId ="";//openId
        String nickname = "";
        String headimgurl = "";
        if(BaseConstants.ACCOUNT_DOMAIN_MP.equals(securityUserDetails.getDomain())){
            String[] username = securityUserDetails.getUsername().split(":");
            if(username.length>=2){
                //获取用户信息
                openId = username[1];
                ResultBody<MpweixinUserExpand> mpweixinUserExpandResultBody = mpweixinServiceClient.selectUserInfo(userId,openId);
                if(mpweixinUserExpandResultBody!=null && mpweixinUserExpandResultBody.getCode() == ResultEnum.OK.getCode()){
                    mpweixinUserExpand = mpweixinUserExpandResultBody.getData();
                }
            }
        }
        if(mpweixinUserExpand!=null){
            nickname = mpweixinUserExpand.getNickname()==null?UserConstants.nickName:mpweixinUserExpand.getNickname();
            headimgurl = mpweixinUserExpand.getHeadimgurl()==null?UserConstants.headImageUrl:mpweixinUserExpand.getHeadimgurl();
        }
        // 获取订单信息
        Orderr order = orderService.getById(orderId);
        if (order == null) {
            log.error("xiaoc>> 获取订单详情失败，orderId: {}", orderId);
            return ResultBodyUtils.failed("订单不存在");
        }
        //返回对象
        OrderDetail orderDetail = BeanConvertUtils.copy(order, OrderDetail.class);
        // 获取订单商品信息
        List<OrderGoods> listOrderGoods = orderGoodsService.listByOrderId(orderId,null);
        orderDetail.setListOrderGoods(listOrderGoods);
        if( BaseConstants.ACCOUNT_DOMAIN_MP.equals(securityUserDetails.getDomain()) && (order.getStatus()==1 || StringUtils.isEmpty(order.getPhone()))){
            // 获取用户历史最近一条订单信息
            Orderr orderOld = orderService.getLastOne(userId);
            log.info(">>minjie 获取userId:{}最近一次订单:{}",userId,orderOld);
            if (orderOld != null) {
                orderDetail.setReceiver(orderOld.getReceiver());
                orderDetail.setReceiverHeadimgurl(orderOld.getReceiverHeadimgurl());
                orderDetail.setPhone(orderOld.getPhone());
            }else{
                orderDetail.setReceiver(securityUserDetails.getNickName()==null?UserConstants.nickName:securityUserDetails.getNickName());
                orderDetail.setReceiverHeadimgurl(securityUserDetails.getAvatar()==null?UserConstants.headImageUrl:securityUserDetails.getAvatar());
            }
        }
        if(order.getUserId()==null || order.getUserId() == 0){
            //C端扫码查看
            if(BaseConstants.ACCOUNT_DOMAIN_MP.equals(securityUserDetails.getDomain())){
                String unionid = ""; //unionid
                if(order.getPayType() == 2 || order.getPayType() == 3 || order.getPayType() == 5){//线下收银的时候添加会员业绩
                    if(openId!=""){
                        ResultBody<MpweixinUser> mpweixinUserResultBody = mpweixinServiceClient.selectMpUserInfo(openId);
                        if(mpweixinUserResultBody != null && mpweixinUserResultBody.getCode() == ResultEnum.OK.getCode()){
                            MpweixinUser mpweixinUser = mpweixinUserResultBody.getData();
                            log.info(">>minjie 查询查看订单人信息mpweixinUser："+JsonUtils.Obj2Str(mpweixinUser));
                            if(mpweixinUser!=null){
                                unionid = mpweixinUser.getUnionid();
                            }
                        }
                    }
                    if(unionid!=""){
                        orderStats1Service.createOrUpdate(unionid,userId,orderDetail.getStoreId(),
                                nickname,headimgurl,orderDetail.getPhone(),orderDetail.getPrice(),0);
                    }
                }
                if(order.getStatus() == 4){//查看收据时指定是谁
                    //更新用户id
                    UpdateWrapper<Orderr> orderrUpdateWrapper = new UpdateWrapper<>();
                    orderrUpdateWrapper.eq("order_id",orderId);
                    Orderr newOrder = new Orderr();
                    newOrder.setUserId(userId);
                    if(mpweixinUserExpand!=null){
                        newOrder.setReceiver(nickname);
                        newOrder.setReceiverHeadimgurl(headimgurl);
                    }else{
                        newOrder.setReceiver(UserConstants.receiver);
                        newOrder.setReceiverHeadimgurl(UserConstants.headImageUrl);
                    }
                    orderService.update(newOrder,orderrUpdateWrapper);
                    orderDetail.setUserId(userId);
                    if(StringUtils.isEmpty(orderDetail.getReceiver()))
                        orderDetail.setReceiver(newOrder.getReceiver());
                    if(StringUtils.isEmpty(orderDetail.getReceiverHeadimgurl()))
                        orderDetail.setReceiverHeadimgurl(newOrder.getReceiverHeadimgurl());
                    if(listOrderGoods!=null && listOrderGoods.size()>0){
                        for(OrderGoods orderGoods:listOrderGoods){
                            //更新指定谁的权限
                            UpdateWrapper<OrderGoods> orderGoodsUpdateWrapper2 = new UpdateWrapper<>();
                            orderGoodsUpdateWrapper2.eq("order_goods_id",orderGoods.getOrderGoodsId());
                            OrderGoods orderGoods2 = new OrderGoods();
                            orderGoods2.setUserId(orderDetail.getUserId());
                            orderGoodsService.update(orderGoods2,orderGoodsUpdateWrapper2);
                            //查询更新核销信息
                            if(mpweixinUserExpand!=null){
                                UpdateWrapper<OrderWriteOffLog> orderWriteOffLogUpdateWrapper = new UpdateWrapper<>();
                                orderWriteOffLogUpdateWrapper.eq("order_goods_id",orderGoods.getOrderGoodsId());
                                OrderWriteOffLog orderWriteOffLog = new OrderWriteOffLog();
                                orderWriteOffLog.setReceiver(nickname);
                                orderWriteOffLog.setReceiverHeadimgurl(headimgurl);
                                orderWriteOffLogService.update(orderWriteOffLog,orderWriteOffLogUpdateWrapper);
                            }
                        }
                    }
                }
            }
            //B端用户查看
            if(BaseConstants.ACCOUNT_DOMAIN_USER.equals(securityUserDetails.getDomain())){
                //如果是B端用户查看流水详情
                //使用默认的头像
                orderDetail.setReceiver(UserConstants.receiver);
                orderDetail.setReceiverHeadimgurl(UserConstants.headImageUrl);
            }
        }

        //获取权益id列表
        List<Long> orderGoodsIdList = new ArrayList<>();
        if(listOrderGoods!=null && listOrderGoods.size()>0){
            for(OrderGoods orderGoods:listOrderGoods){
                orderGoodsIdList.add(orderGoods.getOrderGoodsId());
            }
        }
        //获取门店信息
        ResultBody<Store> retStore = storeServiceClient.getStore(order.getStoreId());
        if (retStore.getCode() == ResultEnum.OK.getCode() && retStore.getData() != null) {
            Store store = retStore.getData();
            orderDetail.setStoreName(store.getName());
            orderDetail.setStorePhone(store.getStorePhone());
        } else {
            log.info("xiaoc>> 获取门店信息失败，storeId: {}", order.getStoreId());
        }

        //订单未付款
        if (order.getStatus() == 1) {
            int shutTimes = 30 * 60;//30分钟内关闭订单
            Long timestamp = (new Date().getTime()-orderDetail.getCt().getTime())/1000;
            if((shutTimes - timestamp.intValue())>0){
                orderDetail.setShutTimeSecond(shutTimes - timestamp.intValue());

                // 未计算余额支付时
                if(order.getPayBalances() <= 0 ) {
                    // C端查看时
                    if (BaseConstants.ACCOUNT_DOMAIN_MP.equalsIgnoreCase(securityUserDetails.getDomain())) {
                        // 获取用户钱包信息
                        ResultBody<MpweixinUserWallet> mpweixinUserWalletResultBody = mpweixinServiceClient.selectUserWallet(securityUserDetails.getUserId());
                        if (mpweixinUserWalletResultBody != null && mpweixinUserWalletResultBody.getCode() == ResultEnum.OK.getCode()) {
                            MpweixinUserWallet mpweixinUserWallet = mpweixinUserWalletResultBody.getData();
                            if (mpweixinUserWallet != null) {
                                orderDetail.setPayBalances(NumberUtils.min(mpweixinUserWallet.getBalance(), orderDetail.getPrice()));
                            }
                        }
                        // 支付金额
                        orderDetail.setPayReady(orderDetail.getPrice() - orderDetail.getPayBalances());
                    }
                }
                if (orderDetail.getPayReady()>0 && BaseConstants.ACCOUNT_DOMAIN_MP.equalsIgnoreCase(securityUserDetails.getDomain())) {
                    String[] arrUsername = securityUserDetails.getUsername().split(":"); // username格式为：公众号appid:openid
                    if (arrUsername.length >= 2) {
                        ResultBody<PayInfoVO> retPayInfoVO = yunStPaymentServiceClient.consumeApply(securityUserDetails.getUserId(),
                                orderDetail.getOrderId(), orderDetail.getPayReady(), YunstConstants.PAY_METHOD_WEIXIN, arrUsername[1], OrderConstants.PAY_OUTTIME);
                        if(retPayInfoVO!=null && retPayInfoVO.getCode() == ResultEnum.OK.getCode()){
                            PayInfoVO payInfoVO = retPayInfoVO.getData();
                            PayInfo payInfo = BeanConvertUtils.copy(payInfoVO, PayInfo.class);
                            payInfo.setOrderId(orderDetail.getOrderId());
                            payInfo.setPayReady(orderDetail.getPayReady());
                            orderDetail.setPayInfo(payInfo);
                        }
                    } else {
                        log.error("xiaoc>> 更新订单并获取支付信息失败，从缓存中获取微信用户openid失败，username: {}", securityUserDetails.getUsername());
                    }
                }
            }
        }

        // 如果订单已支付过
        if (order.getStatus() >= 2) {
            // 如果支付类型为微信支付
            if(orderDetail.getPayType() == 1 && orderDetail.getPayReady() > 0) {
                // 获取支付时间
                ResultBody<PayInfoVO> retPayInfoVO = yunStPaymentServiceClient.paymentInfo(orderId);
                if (retPayInfoVO.getCode() == ResultEnum.OK.getCode() && retPayInfoVO.getData() != null) {
                    orderDetail.setPayTime(retPayInfoVO.getData().getCt());
                }
            } else { // 其它为现金或刷卡支付
                orderDetail.setPayTime(orderDetail.getCt());
            }
        }
        if(order.getStatus() == 2){
            orderDetail.setIsRefundable(1);//如果是已付款初始化都是可以退款的
            //查询是否可以退款
            if(orderDetail.getActId()!=null){
                ResultBody<Act> refAct = actServiceClient.selectActByActId(orderDetail.getActId());
                if (refAct != null && refAct.getCode() == ResultEnum.OK.getCode()) {
                    Act act = refAct.getData();
                    if(act != null){
                        orderDetail.setIsRefundable(act.getIsRefundable());//可否退款状态
                    }
                }
            }
        }else{//其他情况初始情况都是不可退款的
            orderDetail.setIsRefundable(0);
        }
        //如果是已核销,获取最新核销接口
        if (order.getStatus() >= 4) {
            if(orderGoodsIdList !=null && listOrderGoods.size()>0){
                QueryWrapper<OrderWriteOffLog> orderWriteOffLogQueryWrapper = new QueryWrapper<>();
                orderWriteOffLogQueryWrapper.in("order_goods_id",orderGoodsIdList);
                orderWriteOffLogQueryWrapper.orderByDesc("ct");
                orderWriteOffLogQueryWrapper.last("LIMIT 1");
                OrderWriteOffLog orderWriteOffLog = orderWriteOffLogService.getOne(orderWriteOffLogQueryWrapper);
                if(orderWriteOffLog!=null){
                    orderDetail.setWriteOffName(orderWriteOffLog.getUserName());
                    orderDetail.setWriteOffTime(orderWriteOffLog.getCt());
                }
            }else{
                orderDetail.setWriteOffName(order.getCashierName());
                orderDetail.setWriteOffTime(order.getWritOffTime());
            }
        }
        // 如果订单已退款
        if (order.getStatus() == 6) {
            // 获取退款信息
            OrderRefund orderRefund = orderRefundService.getLastOne(orderId, 4);
            if (orderRefund != null) {
                orderDetail.setRefundType(orderRefund.getType());
                orderDetail.setRefundTime(orderRefund.getCt());
                orderDetail.setRefundReason(orderRefund.getReason());
                orderDetail.setRefundExplain(orderRefund.getExplainn());
            }
        }
        //B端查看
        if(BaseConstants.ACCOUNT_DOMAIN_USER.equalsIgnoreCase(securityUserDetails.getDomain())) {
            //拨号记录
            List<ContactList> contactLists = new ArrayList<>();
            QueryWrapper<OrderContactLog> contactLogQueryWrapper = new QueryWrapper<>();
            contactLogQueryWrapper.eq("order_id",orderId);
            contactLogQueryWrapper.orderByDesc("ct");
            List<OrderContactLog> orderContactLogList = orderContactLogService.list(contactLogQueryWrapper);
            if(orderContactLogList.size()>0){
                OK:for(int i=0;i<orderContactLogList.size();i++){
                    ContactList contactList = new ContactList();
                    contactList.setStoreStaffName(orderContactLogList.get(i).getStaffName());
                    contactList.setCt(orderContactLogList.get(i).ct);
                    contactLists.add(contactList);
                    if(i==2)break OK;
                }
            }
            orderDetail.setContactList(contactLists);
        }
        //查看是否需要评价
        QueryWrapper<ReserveOrder> reserveOrderQueryWrapper = new QueryWrapper<>();
        reserveOrderQueryWrapper.eq("order_id",orderId);
        reserveOrderQueryWrapper.orderByDesc("ct");
        reserveOrderQueryWrapper.last("LIMIT 1");
        ReserveOrder reserveOrder = reserveOrderService.getOne(reserveOrderQueryWrapper);
        orderDetail.setIsEvaluate(0);
        orderDetail.setOrderEvaluateId(0L);
        if(reserveOrder!=null){
            orderDetail.setIsEvaluate(1);
            QueryWrapper<OrderEvaluate> orderEvaluateQueryWrapper = new QueryWrapper<>();
            orderEvaluateQueryWrapper.eq("order_id",orderId);
            orderEvaluateQueryWrapper.last("LIMIT 1");
            OrderEvaluate orderEvaluate = orderEvaluateService.getOne(orderEvaluateQueryWrapper);
            if(orderEvaluate!=null){
                orderDetail.setOrderEvaluateId(orderEvaluate.getEvaluateId());
            }
        }else {
            orderDetail.setIsEvaluate(0);
        }
        return ResultBodyUtils.ok(orderDetail);
    }

    /**
     * 获取订单对应的二维码
     * @param orderId
     * @return
     */
    @PostMapping("infoQrcode")
    public ResultBody infoQrcode(@RequestParam("orderId") long orderId) {
        // 获取订单信息
        Orderr order = orderService.getById(orderId);
        if (order == null) {
            log.error("xiaoc>> 获取订单详情失败，orderId: {}", orderId);
            ResultBodyUtils.failed("订单不存在");
        }

        String orderQrcodeStr = redisUtils.get(OrderConstants.REDIS_QRCODE_ + orderId);
        OrderQrcode orderQrcode = JsonUtils.str2Bean(orderQrcodeStr, OrderQrcode.class);
        if(orderQrcode == null) {
            // 获取二维码链接
            QrcodeParam qrcodeParam = new QrcodeParam();
            qrcodeParam.setExpire_seconds(3 * 24 * 60 * 60); // 有效时间，单位秒
            qrcodeParam.setAction_name("QR_STR_SCENE"); // 临时字符串参数
            ActionInfo actionInfo = new ActionInfo();
            Scene scene = new Scene();
            scene.setScene_str(OrderConstants.ORDER_QRCODE_SCENESTR_ + orderId);
            actionInfo.setScene(scene);
            qrcodeParam.setAction_info(actionInfo);
            ResultBody<QrcodeTicket> respQrcodeTicket = mpweixinApiServiceClient.createQrcode(JsonUtils.Obj2Str(qrcodeParam));
            if (respQrcodeTicket.getCode() != ResultEnum.OK.getCode()) { // 获取生成二维失败
                return respQrcodeTicket;
            }
            QrcodeTicket qrcodeTicket = respQrcodeTicket.getData();

            orderQrcode = new OrderQrcode();
            orderQrcode.setOrderId(orderId);
            try {
                orderQrcode.setQrcodeUrl(String.format("%s%s", "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=", URLEncoder.encode(qrcodeTicket.getTicket(), "UTF-8")));
            } catch (Exception e) {
                e.printStackTrace();
                log.info("xiaoc>> 对ticket进行encode异常，取消encode");
                orderQrcode.setQrcodeUrl(String.format("%s%s", "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=", qrcodeTicket.getTicket()));
            }
            orderQrcode.setQrcodeContent(qrcodeTicket.getUrl());

            // 获取门店信息
            List<OrderGoods> listOrderGoods = orderGoodsService.listByOrderId(orderId, null);
            if (listOrderGoods.size() > 0) {
                long storeId = listOrderGoods.get(0).getStoreId();
                ResultBody<Store> respStore = storeServiceClient.getStore(storeId);
                if (respStore.getCode() == ResultEnum.OK.getCode()) {
                    orderQrcode.setStoreNam(respStore.getData().getName());
                }
            }
            // 缓存至redis
            redisUtils.set(OrderConstants.REDIS_QRCODE_ + orderId, JsonUtils.Obj2Str(orderQrcode), 3 * 24 * 60 * 60);
        }

        // 设置订单信息
        orderQrcode.setPayType(order.getPayType());
        orderQrcode.setPrice(order.getPrice());
        orderQrcode.setStatus(order.getStatus());

        return ResultBodyUtils.ok(orderQrcode);
    }

    /**
     * 查询门店交易列别
     */
    @PostMapping("/listorder")
    public ResultBody listOrder(@RequestParam(value = "page", defaultValue = "1") int page,
                                @RequestParam(value = "limit", defaultValue = "10") int limit,
                                @RequestParam("storeId") Long storeId){
        QueryWrapper<Orderr>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("store_id",storeId);
        IPage<Orderr> page1 = orderService.page(new Page<>(page, limit), queryWrapper);
        if (page1.getTotal()==0)return ResultBodyUtils.failed("店铺没有交易信息");
        return ResultBodyUtils.ok(page1);
    }
}
